package com.huawei.statistics.exception;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by XuZhanSi on 2016/11/22 0022.
 * 全局异常类
 */
public class GlobalException implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView=new ModelAndView();
        if(e.getClass().getSimpleName().equals("UnauthorizedException")){
         /*   if(isAjaxRequest(httpServletRequest)) {
                try {
                    WebUtils.toHttp(httpServletResponse).sendError(403);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }*/
            modelAndView.setViewName("com/error/unauthoryError");
        }else{
            modelAndView.setViewName("com/error/error");
        }
        e.printStackTrace();
        modelAndView.addObject("error",e.getMessage());
        return modelAndView;
    }
    private Boolean isAjaxRequest(HttpServletRequest httpRequest) {
        if(StringUtils.equalsIgnoreCase("XMLHttpRequest", httpRequest.getHeader("X-Requested-With"))){
            return true;
        }
        return false;
    }
}
